package com.bill99.http.util;

import com.bill99.util.DateUtil;
import com.bill99.util.EmailUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClient {

	private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class);

	private final String TABLEAU_AUTH_HEADER = "X-Tableau-Auth";

	public Object post(String url, List<BasicNameValuePair> params) {
		LOGGER.info("HTTP client post access. url={}, params={}", url, JsonUtil.convert2Json(params));
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(url);
		Object result = null;
		try {
			method.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			HttpResponse response = httpClient.execute(method);
			Map<String, Object> map = JsonUtil.convert2Object(EntityUtils.toString(response.getEntity(), "UTF-8"), new HashMap<String, Object>());
			if (map == null) {
				LOGGER.error("can not convert result to map. result={}", EntityUtils.toString(response.getEntity(), "UTF-8"));
			} else {
				if (!"10000".equals(map.get("code"))) {
					LOGGER.error("invoke rest error. code={}, message={}.", map.get("code"), map.get("message"));
				} else {
					result = map.get("content");
				}
			}
		} catch (Exception e) {
			LOGGER.error("invoke rest api error .", e);
		} finally {
			LOGGER.info("invoke rest result = {}", result);
			LOGGER.info("HTTP client post return.");
		}

		return result;
	}

	//发送get请求
	public Object get(String url,String token){

		CloseableHttpClient httpCilent2 = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000)   //设置连接超时时间
                .setConnectionRequestTimeout(50000) // 设置请求超时时间
                .setSocketTimeout(50000)
                .setRedirectsEnabled(true)//默认允许自动重定向
                .build();
        HttpGet httpGet2 = new HttpGet(url);
        httpGet2.setConfig(requestConfig);
        httpGet2.setHeader(TABLEAU_AUTH_HEADER, token);
        String srtResult = "";
        try {
            HttpResponse httpResponse = httpCilent2.execute(httpGet2);
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
                LOGGER.info("接口访问成功，code : 200;返回内容 : "+srtResult);
            }else if(httpResponse.getStatusLine().getStatusCode() == 400){
            	LOGGER.info("获取票证失败，code : 400");
            }else if(httpResponse.getStatusLine().getStatusCode() == 500){
            	LOGGER.info("获取票证失败，code : 500");
            }else {
            	LOGGER.info("获取票证失败，code:"+httpResponse.getStatusLine().getStatusCode());
			}
        } catch (IOException e) {
        	LOGGER.error("tableau get请求出错 : ", e);
        }finally {
            try {
                httpCilent2.close();
            } catch (IOException e) {
            	LOGGER.error("tableau io流关闭出错 : ", e);
            }
        }


		return srtResult;
	}


	//发送get请求
		public void getPic(String url,String token,String uploadPath)throws Exception{

			CloseableHttpClient httpCilent2 = HttpClients.createDefault();
	        RequestConfig requestConfig = RequestConfig.custom()
	                .setConnectTimeout(50000)   //设置连接超时时间
	                .setConnectionRequestTimeout(50000) // 设置请求超时时间
	                .setSocketTimeout(50000)
	                .setRedirectsEnabled(true)//默认允许自动重定向
	                .build();
	        HttpGet httpGet2 = new HttpGet(url);
	        httpGet2.setConfig(requestConfig);
	        httpGet2.setHeader(TABLEAU_AUTH_HEADER, token);
	        String srtResult = "";
	        try {
	            HttpResponse httpResponse = httpCilent2.execute(httpGet2);
	            if(httpResponse.getStatusLine().getStatusCode() == 200){
//	                srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
	                InputStream  in = httpResponse.getEntity().getContent();
	             // 输出的文件流保存图片至本地
					String nowday = DateUtil.formatDateTime("yyyyMMdd", new Date());
					OutputStream os = new FileOutputStream(uploadPath+"99bill_ZX_dashboard_"+nowday+".png");
	                //保存图片
	                try {
	                	byte b[] = new byte[1024];
	                int len = in.read(b);
	                while (len > 0) {
//	                	bout.write(b, 0, len);  
	                	os.write(b, 0, len);
	                	len = in.read(b);
	                	}
	                } catch (Exception e) {
	                	throw e;
	                	} finally {
//	                		bout.close();  	        
	                		in.close();
	                }

	                LOGGER.info("接口访问成功，code : 200;返回内容 : "+srtResult);
	            }else if(httpResponse.getStatusLine().getStatusCode() == 400){
	            	LOGGER.info("获取票证失败，code : 400");
	            }else if(httpResponse.getStatusLine().getStatusCode() == 500){
	            	LOGGER.info("获取票证失败，code : 500");
	            }else {
	            	LOGGER.info("获取票证失败，code:"+httpResponse.getStatusLine().getStatusCode());
				}
	        } catch (IOException e) {
	        	LOGGER.error("tableau get请求出错 : ", e);
	        }finally {
	            try {
	                httpCilent2.close();
	            } catch (IOException e) {
	            	LOGGER.error("tableau io流关闭出错 : ", e);
	            }
	        }

		}

	public void getPics(String url,String token,String uploadPath)throws Exception{

		CloseableHttpClient httpCilent2 = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(50000)   //设置连接超时时间
				.setConnectionRequestTimeout(50000) // 设置请求超时时间
				.setSocketTimeout(50000)
				.setRedirectsEnabled(true)//默认允许自动重定向
				.build();
		HttpGet httpGet2 = new HttpGet(url);
		httpGet2.setConfig(requestConfig);
		httpGet2.setHeader(TABLEAU_AUTH_HEADER, token);
		String srtResult = "";
		try {
			HttpResponse httpResponse = httpCilent2.execute(httpGet2);
			if(httpResponse.getStatusLine().getStatusCode() == 200){
//	                srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
				InputStream  in = httpResponse.getEntity().getContent();
				// 输出的文件流保存图片至本地
				OutputStream os = new FileOutputStream(uploadPath+".png");
				//保存图片
				try {
					byte b[] = new byte[1024];
					int len = in.read(b);
					while (len > 0) {
//	                	bout.write(b, 0, len);
						os.write(b, 0, len);
						len = in.read(b);
					}
				} catch (Exception e) {
					throw e;
				} finally {
//	                		bout.close();
					in.close();
				}

				LOGGER.info("接口访问成功，code : 200;返回内容 : "+srtResult);
			}else if(httpResponse.getStatusLine().getStatusCode() == 400){
				LOGGER.info("获取票证失败，code : 400");
			}else if(httpResponse.getStatusLine().getStatusCode() == 500){
				LOGGER.info("获取票证失败，code : 500");
			}else {
				LOGGER.info("获取票证失败，code:"+httpResponse.getStatusLine().getStatusCode());
			}
		} catch (IOException e) {
			LOGGER.error("tableau get请求出错 : ", e);
		}finally {
			try {
				httpCilent2.close();
			} catch (IOException e) {
				LOGGER.error("tableau io流关闭出错 : ", e);
			}
		}

	}

	public static void main(String[] args) {
		 BASE64Encoder encoder = new sun.misc.BASE64Encoder();   //加密
		 BASE64Decoder decoder = new sun.misc.BASE64Decoder();   //解密
		BufferedImage bi;
		try {
			bi = ImageIO.read(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\99bill_ZX_dashboard_20181029_ziped3.png"));
//            byte[] bytes = ImageTest.bufferedImageTobytes(bi, 0.1f);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(bi, "png", baos);
			byte[] bytes = baos.toByteArray();
			Map<String, String> params = new HashMap();
			params.put("subject","快钱直销商户交易趋势dashboard");
			params.put("whichView","直销商户交易趋势分析");
			params.put("emailAddresses", "jun.li.wb@99bill.com");//收件人列表，多个用','隔开
			params.put("templateId","19718110");//模板ID
			params.put("sendEmailUrl","http://192.168.127.38:8084/email-prepare/sendEmail.do");

           String trim = "data:img/png;base64,"+encoder.encodeBuffer(bytes).trim();
            System.out.println(trim);
            //String trim =new String("")
            //String imgSrc="";
            params.put("imgSrc",trim);
			EmailUtil emailUtil=new EmailUtil();
			emailUtil.send(params);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}




}
